package com.wzy.netty.bio;

import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 描述  :   BIO 通信模式
 * 创建人:    Wzy
 * 创建时间: 2020-06-10  11:58
 */
@Slf4j
public class BioServer2 {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(6666);
        ExecutorService executorService = Executors.newCachedThreadPool();
        log.info("<<<<<<服务器启动>>>>>>");
        while (true) {
            Socket socket = serverSocket.accept();
            log.info("连接到一个客户端");
            executorService.execute(() -> {
                socketHandler(socket);
            });
        }
    }

    public static void socketHandler(Socket socket) {
        try {
            log.info("当前线程id:{},名字:{}", Thread.currentThread().getId(), Thread.currentThread().getName());
            InputStream inputStream = socket.getInputStream();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int readLen = 0;
            while ((readLen = inputStream.read(bytes)) != -1) {
                byteArrayOutputStream.write(bytes, 0, readLen);
            }
            log.info("服务端接收信息:{}", byteArrayOutputStream.toString("UTF-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
